<template>
    <div class="box">
        <video src="" id="camera" class="camera" :width="videoWidth" :height="videoHeight"></video>
        <canvas id="photo" class="photo" :width="videoWidth" :height="videoHeight"></canvas>
        <div>
            <el-button @click="photograph">拍照</el-button>
            <el-button @click="openCamera" v-if="flag">打开摄像头</el-button>
            <el-button @click="closeCamera" v-else>关闭摄像头</el-button>
            <el-button @click="reset">重置</el-button>
            <el-button @click="submit">提交</el-button>
        </div>
    </div>
</template>

<script>
    export default {
        data(){
            return{
                flag:false,
                videoWidth:500,
                videoHeight:350,
                camera:null,
                paint:null,
                canvas:null,
                ImageSrc:''
            }
        },
        methods:{
            // 打开摄像头
            openCamera(){
                this.flag = false;
                // 获取video标签
                this.camera = document.querySelector('.camera');
                // 做兼容处理 如果navigator.mediaDevices是undefined
                if(navigator.mediaDevices === undefined){
                    // 将它设置为一个空对象
                    navigator.mediaDevices = {};
                }
                // 如果navigator.mediaDevices.getUserMedia 为undefined
                if(navigator.mediaDevices.getUserMedia === undefined){
                    navigator.mediaDevices.getUserMedia = function(constraints){
                        // 获取一下不同的浏览器的getUserMedia
                        let getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia;
                        // 如果getUserMedia不存在
                        if(!getUserMedia){
                            // 给用户发送一个提醒
                            return Promise.reject(new Error("请更换浏览器！"))
                        }
                        return new Promise((resolve,reject)=>{
                            // 改变指向 让它指向constraints
                            getUserMedia.call(navigator,constraints,resolve,reject);
                        })
                    }
                }
                 // constraints 传入音频视频文件信息
                const constraints = {
                    audio:false,
                    video:{
                        width:this.videoWidth,
                        height:this.videoHeight
                    }
                }
                // 正式调用摄像头
                navigator.mediaDevices.getUserMedia(constraints).then((res)=>{
                    // res为实时数据流
                    console.log(res);
                    console.log(this.camera);
                    // 如果在video中可以找到srcObject
                    if("srcObject" in this.camera){
                        // 让video的srcObject等于实时数据流
                        this.camera.srcObject = res;
                    }else{//如果在video中找不到srcObject
                        // window.URL.createObjectURL 创建一个新的对象 URL
                        this.camera.src = window.URL.createObjectURL(res);
                    }
                    //onloadedmetadata 视频数据加载完毕后就会触发
                    this.camera.onloadedmetadata = function(){
                        console.log('视频元数据加载完毕！');
                        this.play();
                    }
                }).catch((err)=>{
                    console.log(err);
                })
            },
            // 关闭摄像头
            closeCamera(){
                if(this.camera && this.camera !== null){
                    this.camera.srcObject.getTracks()[0].stop();
                    this.flag = true;
                }
            },
            // 拍照
            photograph(){
                this.canvas = document.querySelector('.photo');
                this.paint = this.canvas.getContext('2d');
                this.paint.drawImage(
                    this.camera,0,0,100,100//(img标签，起始位置，宽，高)
                );
                this.ImageSrc = this.canvas.toDataURL('image/png');//toDataURL返回值是包含图片信息的url（base64）
            },
            // 提交
            submit(){
                this.$router.push({name:'studentsinfo',query:{ImageSrc:this.ImageSrc}})
            },
            // 重置
            reset(){
                // 重新获取画布和画笔
                this.canvas = document.querySelector('.photo');
                this.paint = this.canvas.getContext('2d');
                this.paint.clearRect(0,0,this.videoWidth,this.videoHeight);//参数一二是清除的起始位置 参数三四是结束位置
            }
        },
        mounted(){
            this.openCamera();
        }
    }
</script>

<style lang="scss" scoped>

</style>